package com.oocl.jpa.Aspect;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import com.oocl.jpa.pojo.Customer;

/**
 * @description: 环绕通知
 * @author  XIEMI2
 * @date Aug 9, 2017 6:57:11 PM
 * @version 1.0
 * execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)

 */
@Component
@Aspect
public class DigestAspect {
	private final String register = "execution(* com.oocl.jpa.service.CustomerService.register(..))";
	private final String login = "execution(* com.oocl.jpa.service.CustomerService.login(..))";
	
	//为应用程序提供信息摘要算法的功能
	private MessageDigest disgest;

	public DigestAspect() {
		
		System.out.println("--------------加密算法执行开始----------------");
		
		try {
			disgest = MessageDigest.getInstance("SHA-1");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}
	
	//Advice在业务执行的插入点或时机，如方法的前后等
	/**
	 * Object[] getArgs：返回目标方法的参数
	 * @param point
	 * @return
	 */
	@Around(value=register)
	public Object register(ProceedingJoinPoint point){
		System.out.println("--------------register 加密算法执行开始----------------");
		Object o = null;
		Customer c = (Customer)point.getArgs()[0];
		c.setPassword(process(c.getPassword()));
		try {
			o = point.proceed(new Object[]{c});
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return o;
	}
	
	@Around(value=login)
	public Object login(ProceedingJoinPoint point){
		System.out.println("--------------login 加密算法执行开始----------------");
		Object o = null;
		String s = (String) point.getArgs()[1];
		String ss = process(s);
		
		try {
			o = point.proceed(new Object[]{point.getArgs()[0], ss});
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return o;
	}
	
	
	
	//本方法内部调用，不要写为 public
	private String process(String s){
		String ss = null;
		System.out.println("--------------加密算法执行开始 原来s----------------"+s);
		try {
			byte[] bs = disgest.digest(s.getBytes("ISO-8859-1"));
			ss = new String(bs, "ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("--------------加密算法执行 之后----------------"+ss);
		return ss;
	}
	
}


